package com.maysham.tripod.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class FileUtil {

    public static File compressTar(String sourceDir, String targetDir, String targetName) throws IOException {
        File targetDirFile = new File(targetDir);
        if (!targetDirFile.exists()) {
            if (!targetDirFile.mkdirs()) {
                throw new IOException("目标地址不存在");
            }
        }
        File sourceDirFile = new File(sourceDir);
        if (!sourceDirFile.exists() || !sourceDirFile.isDirectory()) {
            throw new IOException("操作文件目录不存在");
        }
        String tarFilePath = targetDir + File.separator + targetName;
        File tarFile = new File(tarFilePath);
        TarArchiveOutputStream outputStream = new TarArchiveOutputStream(new FileOutputStream(tarFile));
        outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        Map<String, File> map = new HashMap<>();
        list(sourceDirFile, null, map);
        map.forEach((k, item) -> {
            try {
                if (!item.canRead()) {
                    return;
                }
                TarArchiveEntry entry = new TarArchiveEntry(item, k.substring(k.indexOf("/")));
                outputStream.putArchiveEntry(entry);
                try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(item))) {
                    byte[] buffer = new byte[1024 * 5];
                    int len = -1;
                    while ((len = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    outputStream.closeArchiveEntry();
                } catch (Exception e) {
                    log.error("压缩文件失败:{}", item.getName(), e);
                }
            } catch (Exception e) {
                log.error("压缩文件失败", e);
            }

        });
        outputStream.finish();
        outputStream.close();
        return tarFile;
    }

    private static void list(File f, String parent, Map<String, File> map) {
        String name = f.getName();
        if (parent != null) {
            name = parent + "/" + name;//设置在zip包里的相对路径
        }
        if (f.isFile()) {
            map.put(name, f);
        } else if (f.isDirectory()) {
            File[] files = f.listFiles();
            if (files == null) {
                return;
            }
            for (File file : files) {
                list(file, name, map);
            }
        }
    }

    public static String readToBinary(File file) {

        return null;
    }
}
